package taller2.view.windows.CreatorWindows;

import java.awt.GridBagLayout;

import taller2.controller.listeners.WindowClosingListener;
import taller2.interfaces.AlgorithmApplicator;
import taller2.interfaces.ChangeableWindow;
import taller2.interfaces.Graph;
import taller2.model.factorys.GraphFactory;
import taller2.utils.Constants;
import taller2.utils.Point;
import taller2.view.draws.DrawingArea;
import taller2.view.draws.GraphDrawer;
import taller2.view.menus.CreatorMenus.GraphCreatorMenu;
import taller2.view.windows.MyWindow;

public class GraphCreatorWindow {
	protected Graph mainGraph,localGraph;
	protected DrawingArea localArea;
	protected MyWindow window;
	protected GraphDrawer drawer;
	protected DrawingArea area;
	protected AlgorithmApplicator algorithmApplicator;
	protected ChangeableWindow mWindow;
	protected GraphCreatorMenu selector;
	
	public GraphCreatorWindow(ChangeableWindow window, Graph mainGraph, DrawingArea area, AlgorithmApplicator algorithmApplicator) {
		this.area = area;
		this.mainGraph = mainGraph;
		this.algorithmApplicator = algorithmApplicator;
		this.mWindow = window;
		
		this.window = new MyWindow("ventana");
		this.window.halfScreen();
		this.window.hideOnClose();
		this.window.setResizable(false);
		
		mWindow.getBrowser().stopAutoscroll();
		mWindow.getMenu().setAutohighlightButton(false);
		this.window.addWindowListener(new WindowClosingListener(window));

		if(mainGraph.isDirected())
			this.localGraph = GraphFactory.directedGraphInstance(mainGraph);
		else
			this.localGraph = GraphFactory.undirectedGraphInstance(mainGraph);

		this.drawer = new GraphDrawer(this.localGraph,Constants.selectedColor,Constants.unSelectedColor);	
		
		this.localArea = new DrawingArea(Constants.backgroundPath,drawer);
		this.selector = createGraphCreatorMenu();
		
		this.window.setLayout(new GridBagLayout());
		this.window.addComponent(this.localArea, 1, 1, new Point(0, 0));
		this.window.addComponent(selector, 1, 0, new Point(0, 1));
		this.window.redraw();
	}
		
	protected GraphCreatorMenu createGraphCreatorMenu(){
		return (new GraphCreatorMenu(this.localArea,this.localGraph, this, this.algorithmApplicator));
	}
	
	// sets the local graph as the main graph
	public void applyChanges(){
		
		mainGraph.replace(localGraph);
		window.setVisible(false);
		window.dispose();
		area.getDrawer().loadSelection();
		area.repaint();
		
		if(algorithmApplicator != null){
			algorithmApplicator.reset();
			algorithmApplicator.solveProblem(mainGraph);
		}
	}

	// saves the graph to a file
	public void save(String path) {
		localGraph.save(path);
	}
	
	// loads the graph from the file
	public Graph load(String path) {
		localGraph.load(path);
		localArea.getDrawer().loadSelection();
		localArea.repaint();
		
		return null;
	}

}
